home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: news.eds.co.nz!usenet
- From: Ross Smith <ross.smith@nz.eds.com>
- Subject: Re: STL
- Content-Type: text/plain; charset=us-ascii
- Sender: usenet@nz.eds.com (Usenet News Admin)
- Content-Transfer-Encoding: 7bit
- Organization: EDS (New Zealand) Ltd
- Message-ID: <312D41A0.19B7@nz.eds.com>
- References: <4gdgt0$494@netaxs.com> <312B2DEF.65C7@airmail.net>
- X-Mailer: Mozilla 2.0 (WinNT; I)
- Mime-Version: 1.0
- X-Nntp-Posting-Host: crazy-harry.lab.nz.eds.com
- Date: Fri, 23 Feb 1996 04:25:04 GMT
-
- Mark Nelson wrote:
- >
- > Bob Pesavento wrote:
- > >
- > > I'm a newbie with STL and not an expert at C++ so bear with me. Assume a
- > > simplified class:
- > >
- > > class myclass
- > > {
- > > int myint;
- > > float myfloat;
- > >
- > > public:...
- > >
- > > I want use "list" and stuff a bunch of these in using push_back. No
- > > problem so far. But I want the user to be able to select which item to
- > > sort on... myint or myfloat.
- >
- > The sorting is done using operator<(), so you don't have much choice about that.
- > [ bogus solution snipped ]
-
- Not true; sort() can accept a comparison function instead of op<. You need
- to declare the appropriate comparison functions (which must be global
- functions, not members), something like this:
-
- class myclass {
- private:
- int myint;
- float myfloat;
- public:
- // the usual crop of constructors etc
- friend bool CompareByInt(const myclass& x, const myclass& y) {
- return x.myint < y.myint;
- }
- friend bool CompareByFloat(const myclass& x, const myclass& y) {
- return x.myfloat < y.myfloat;
- }
- };
-
- (NB. Whether the friend functions are defined inside or outside the class
- body is unimportant; it's just a style choice.)
-
- Then you can sort a sequence with something like:
-
- sort(sequence.begin(), sequence.end(), CompareByInt);
- sort(sequence.begin(), sequence.end(), CompareByFloat);
-
- However, you can't sort a list using sort(); it has to be a vector or
- deque (because sort() needs random-access iterators, while lists only
- have bidirectional iterators).
-
- --
- Ross Smith ........................................ Wellington, New Zealand
- Work: <mailto:ross.smith@nz.eds.com> ... Home: <mailto:alien@netlink.co.nz>
- "Remember when we told you there was no future? Well, this is it."
- -- Blank Reg
-